/**
*	FPSMeter
*	@author 	Liam O'Donnell 2007-11-25
**/

package com.spikything.utils {

	import flash.display.Sprite;
	import flash.events.TimerEvent;
	import flash.events.Event;
	import flash.text.TextField;
	import flash.text.TextFieldAutoSize;
	import flash.text.TextFormat;
	import flash.utils.Timer;
	import flash.system.System;

	public class FPSMeter extends Sprite {

		private var _tf:TextField;
		private var _fmt:TextFormat;
		private var _timer:Timer;
		private var _frameNum:int;

		public function FPSMeter (color:Number=0xffff00) {
			_fmt = new TextFormat("_sans", 10, color);
			_frameNum = 0;
			init(); 
		}

		private function init ():void {
			_tf = createText();
			addChild(_tf);
			_timer = new Timer(1000);
			_timer.addEventListener(TimerEvent.TIMER, displayFPS, false, 0, true);
			this.addEventListener(Event.ENTER_FRAME, increaseFrame, false, 0, true);
			_timer.start();
		}

		private function displayFPS (te:TimerEvent):void {
			_tf.text = "FPS: " + _frameNum + " \tRAM: " + (Math.round(System.totalMemory/(1024*1024/10))/10) + "MB";
			_frameNum = 0;
		}

		private function increaseFrame (e:Event):void {
			++_frameNum;
		}

		private function createText ():TextField {
			var t:TextField = new TextField();
			t.width = 50;
			t.height = 16;
			t.autoSize = TextFieldAutoSize.LEFT;
			t.selectable = false;
			t.defaultTextFormat = _fmt;
			return t;
		}

		public function set textColor (col:uint):void {
			_tf.textColor = col;
		}
	}
}